import json
import random
import string
from datetime import time

import arrow
import captcha
import requests
from captcha.image import ImageCaptcha
from flask import Blueprint, request, redirect, make_response, Response, jsonify
from application.models.model import User, Role, role_user, BrokerUser
from cache import my_cache
from db_init import db
from swaager_init import siwa, BaseModel
from sqlalchemy.exc import IntegrityError
from flask_login import login_user, login_required, current_user

from tools.broker_api import get_token_by_code
from tools.data_tools import orm2dict, ret_route
from my_config import VIP_END_TIME, LOGIN_APP_MAP

callback = siwa.blueprint("callback", __name__)


@callback.route("/<any(github,gitee):broker>", methods=['get'])
def github_cb(broker):
    code = request.args.get('code')
    token, uid = get_token_by_code(broker, code)

    broker_user = BrokerUser.query.filter_by(broker_uid=uid, broker_name=broker).first()

    if broker_user and broker_user.user:
        login_user(broker_user.user)
        return ret_route(2000)

    return ret_route(2000, data={'broker_id': uid, 'token': token, 'broker': broker})